﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web.UI;
using log4net;

namespace FortuneCookie.EPiServer.SearchAndReplace
{
    /// <summary>
    /// SearchAndReplacePage class
    /// </summary>
    public class SearchAndReplacePage : System.Web.UI.Page
    {

        #region Members

        private readonly ILog _logger = LogManager.GetLogger(typeof(SearchAndReplacePage));

        #endregion Members

        #region Properties

        /// <summary>
        /// Gets the request type
        /// </summary>
        private string RequestType
        {
            get
            {
                return Request.QueryString["rt"];
            }
        }

        /// <summary>
        /// Gets the search and replace id
        /// </summary>
        private Guid SearchAndReplaceId
        {
            get
            {
                return new Guid(Request.QueryString["id"]);
            }
        }

        #endregion Properties

        #region Event handlers

        /// <summary>
        /// Fires when the page is loaded
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            PageLoadController();
        }

        #endregion Event handlers

        #region Methods

        /// <summary>
        /// Page load controller
        /// </summary>
        private void PageLoadController()
        {
            try
            {
                Debug.WriteLine(string.Format("SearchAndReplacePage page requested : {0}", Request.Url.PathAndQuery));

                Response.ContentType = "text/html";
                SearchAndReplace searchAndReplace = new SearchAndReplace { Id = SearchAndReplaceId };
                int[] status = SearchAndReplaceHelper.GetFromCache<int[]>(searchAndReplace);

                if (status == null)
                    return;
                
                StringBuilder html = new StringBuilder();

                using (StringWriter stringWriter = new StringWriter(html))
                {
                    using (HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter))
                    {
                        switch (RequestType)
                        {
                            case "0":
                                SearchAndReplace(textWriter, status);
                                break;
                            case "1":
                                Publish(textWriter, status);
                                break;
                            case "2":
                                Rollback(textWriter, status);
                                break;
                        }
                    }
                }

                string output = html.ToString();
                Debug.WriteLine(string.Format("SearchAndReplacePage response : {0}", output));

                Response.Write(output);
            }
            catch (Exception ex)
            {
                _logger.Error("An exception occured in the SearchAndReplacePage :: PageLoadController", ex);
            }
        }

        /// <summary>
        /// Renders progress for the search and replace
        /// </summary>
        /// <param name="textWriter"></param>
        /// <param name="status"></param>
        private static void SearchAndReplace(HtmlTextWriter textWriter, int[] status)
        {
            textWriter.AddAttribute(HtmlTextWriterAttribute.Class, "sarProgressItem");
            textWriter.RenderBeginTag(HtmlTextWriterTag.Div);
            textWriter.Write(string.Format("{0} : {1}", LanguageHelper.Translate("/searchAndReplacePlugin/pagesSearched"), status[0]));
            textWriter.RenderEndTag();

            textWriter.AddAttribute(HtmlTextWriterAttribute.Class, "sarProgressItem");
            textWriter.RenderBeginTag(HtmlTextWriterTag.Div);
            textWriter.Write(string.Format("{0} : {1}", LanguageHelper.Translate("/searchAndReplacePlugin/pagesUpdated"), status[1]));
            textWriter.RenderEndTag();

            textWriter.AddAttribute(HtmlTextWriterAttribute.Class, "sarProgressItem");
            textWriter.RenderBeginTag(HtmlTextWriterTag.Div);
            textWriter.Write(string.Format("{0} : {1}", LanguageHelper.Translate("/searchAndReplacePlugin/dynamicPropertiesUpdated"), status[2]));
            textWriter.RenderEndTag();
        }

        /// <summary>
        /// Renders progress for pages being published
        /// </summary>
        /// <param name="textWriter"></param>
        /// <param name="status"></param>
        private static void Publish(HtmlTextWriter textWriter, int[] status)
        {
            textWriter.AddAttribute(HtmlTextWriterAttribute.Class, "sarProgressItem");
            textWriter.RenderBeginTag(HtmlTextWriterTag.Div);
            textWriter.Write(string.Format("{0} : {1}", LanguageHelper.Translate("/searchAndReplacePlugin/pagesPublished"), status[1]));
            textWriter.RenderEndTag();
        }

        /// <summary>
        /// Renders progress for pages being rolled back
        /// </summary>
        /// <param name="textWriter"></param>
        /// <param name="status"></param>
        private static void Rollback(HtmlTextWriter textWriter, int[] status)
        {
            textWriter.AddAttribute(HtmlTextWriterAttribute.Class, "sarProgressItem");
            textWriter.RenderBeginTag(HtmlTextWriterTag.Div);
            textWriter.Write(string.Format("{0} : {1}", LanguageHelper.Translate("/searchAndReplacePlugin/pagesRolledBack"), status[1]));
            textWriter.RenderEndTag();
        }

        #endregion Methods

    }
}
